import {
  HTTP
} from "../utils/http.js"
class ClassicModel extends HTTP {
  getLatest(callBack) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        callBack(res)
        this._setLatestIndex(res.index)
        let key=this._getKey(res.index)
        wx.setStorageSync(key,res)
      }
    })
  }
  getClassic(index, nextOrPrevious, sCallBack) {
    // 缓存中寻找orAPI写入到缓存
    let key = nextOrPrevious == 'next' ? this._getKey(index + 1) : this._getKey(index - 1);
    let classic = wx.getStorageSync(key);
    if (!classic) {
      this.request({
        url: 'classic/' + index + '/' + nextOrPrevious,
        success: (res) => {
          wx.setStorageSync(this._getKey(res.index),res)
          sCallBack(res)
        }
      })
    }else{
      sCallBack(classic)
    }
  }


  isFirst(index) {
    return index == 1 ? true : false
  }

  isLatest(index) {
    let latestIndex = this._getLatestIndex()
    return index == latestIndex ? true : false
  }

  getMyFavor(success){
    const parmas={
      url:'classic/favor',
      success:success
    }
    this.request(parmas)
  }

  _setLatestIndex(index) {
    wx.setStorage({
      key: 'latest',
      data: index,
    })
  }

  _getLatestIndex() {
    let index = wx.getStorageSync('latest')
    return index
  }

  _getKey(index) {
    let key = 'classic-' + index
    return key
  }
}

export {
  ClassicModel
}